package com.daxt.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.common.result.PageInfo;
import com.daxt.common.result.PageUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.archives.ArchivesBaseMapper;
import com.daxt.mapper.archives.ArchivesDocExtMapper;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.archives.ArchivesDocValueMapper;
import com.daxt.mapper.archives.ArchivesTypeDocMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.mapper.sys.SystemConfigMapper;
import com.daxt.model.service.archives.result.ArchivesDetails;
import com.daxt.model.service.archives.result.ArchivesList;
import com.daxt.model.service.archives.vo.ArchivesBase;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.archives.vo.ArchivesDocExt;
import com.daxt.model.service.archives.vo.ArchivesDocValue;
import com.daxt.model.service.archives.vo.ArchivesType;
import com.daxt.model.service.archives.vo.ArchivesTypeDoc;
import com.daxt.model.service.base.vo.SystemConfig;
import com.daxt.service.DossierService;

@Service
public class DossierServiceImpl implements DossierService {

	@Autowired
	private ArchivesBaseMapper archivesBaseMapper;
	@Autowired
	private ArchivesDocValueMapper archivesDocValueMapper;
	@Autowired
	private ArchivesDocMapper archivesDocMapper;
	@Autowired
	private ArchivesDocExtMapper archivesDocExtMapper;
	@Autowired
	private ArchivesTypeMapper archivesTypeMapper;
	@Autowired
	private ArchivesTypeDocMapper archivesTypeDocMapper;
	@Autowired
	private SystemConfigMapper systemConfigMapper;
//	@Value(value = "${systemConfig.createNum}")
//	private Integer createNum;

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Result<String> dossierSave(ArchivesDoc archivesDossier) {

		try {
			// archivesDossier.setState("0");
			archivesDossier.setFileType("dossier");
			if (StringUtils.isEmpty(archivesDossier.getDossierId())) {
				archivesDossier.setDossierId(0L);
			}

			/*Map<String, List<ArchivesTypeDoc>> mapkey = new HashMap<>();
			Map<String, List<ArchivesTypeDoc>> map = new HashMap<>();
			List<ArchivesTypeDoc> typeDocs = archivesTypeDocMapper.selectList(null);
			QueryWrapper<ArchivesType> queryType = new QueryWrapper<ArchivesType>();
			queryType.eq("fondsNum", archivesDossier.getfondsNum());
			queryType.eq("typeNum", archivesDossier.getTypeNum());
			List<ArchivesType> types = archivesTypeMapper.selectList(queryType);
			for (ArchivesType archivesType : types) {
				mapkey.put(archivesType.getfondsNum() + ":" + archivesType.getId(), null);
			}
			for (String key : mapkey.keySet()) {
				List<ArchivesTypeDoc> tempList = new ArrayList<ArchivesTypeDoc>();
				// String fileType="";
				for (ArchivesTypeDoc archivesTypeDoc : typeDocs) {
					String typeId = archivesTypeDoc.getTypeId().toString();
					if (key.split(":")[1].equals(typeId)) {
						tempList.add(archivesTypeDoc);

					}
				}
				map.put(key.split(":")[0], tempList);
			}
			List<ArchivesTypeDoc> list = map.get(archivesDossier.getfondsNum());
			Map parseObject = JSON.parseObject(JSON.toJSONString(archivesDossier), Map.class);
			for (ArchivesTypeDoc archivesTypeDoc : list) {
				if (archivesTypeDoc.getExtType().equals(archivesDossier.getFileType())) {
					Object object = parseObject.get(archivesTypeDoc.getExtColumn());
					if (object != null && !StringUtils.isEmpty(object.toString())) {
						String fileKeyword = archivesDossier.getFileKeyword() == null ? ""
								: archivesDossier.getFileKeyword();
						fileKeyword = fileKeyword + (StringUtils.isEmpty(fileKeyword) ? "" : "   ")
								+ (archivesTypeDoc.getColumnComment() + ":" + object.toString());
						archivesDossier.setFileKeyword(fileKeyword);
					}
				}
			}
			*/
			QueryWrapper<SystemConfig> queryWrapperSys = new QueryWrapper<SystemConfig>();
			queryWrapperSys.eq("sysKey", "ARCHIVES_CODE");
			List<SystemConfig> selectList = systemConfigMapper.selectList(queryWrapperSys);
			if (selectList != null && selectList.size() > 0) {
				archivesDossier.setArchivesCode(selectList.get(0).getSysValue());
			}

			archivesDocMapper.insert(archivesDossier);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", "");
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
	}

	@Override
	public Result<ArchivesList> list(Integer pageNum, Integer pageSize, String extType, String fondsNum,
			String condition, String classNum, String state) {
		if (!StringUtils.isEmpty(condition)) {
			Base64 base64 = new Base64();
			try {
				condition = new String(base64.decode(condition), "UTF-8");

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();

			}
		}
		QueryWrapper<ArchivesBase> col = new QueryWrapper<>();
		col.eq("extType", "dossier");
		col.eq("isList", "1");
		List<ArchivesBase> base = archivesBaseMapper.selectList(col);
		List<String> query = new ArrayList<>();
		for (int i = 0; i < base.size(); i++) {
			query.add(base.get(i).getExtColumn());
		}
		Page<ArchivesDoc> page = new Page<ArchivesDoc>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cols", query);
		param.put("fondsNum", fondsNum);
		param.put("typeNum", extType);
		if (!StringUtils.isEmpty(classNum)) {
			param.put("classNum", classNum);
		}

		param.put("state", state);
		List<String> queryCondition = new ArrayList<String>();
		if (!StringUtils.isEmpty(condition) && condition.contains(":")) {
			int indexOf = condition.indexOf("aconcata");
			if (indexOf > 0) {
				String[] split = condition.split("aconcata");
				for (String string : split) {
					if (string.indexOf(":") > 0) {
						String[] split2 = string.split(":");
						if (split2[0].equals("base")) {
							queryCondition.add("a." + split2[1]);
						} else if (split2[0].equals("ext")) {
							queryCondition.add("b." + split2[1]);
						}
					}
				}
			} else {
				if (condition.indexOf(":") > 0) {
					String[] split2 = condition.split(":");
					if (split2[0].equals("base")) {
						queryCondition.add("a." + split2[1]);
					} else if (split2[0].equals("b." + split2[1])) {
						queryCondition.add(condition);
					}
				}
			}
		}
		param.put("fileType", "dossier");
		param.put("query", queryCondition);
		// Page<ArchivesDossier> page=new Page<>(pageNum==null?0:pageNum,
		// pageSize==null?10:pageSize);
		IPage<ArchivesDoc> info = archivesDocMapper.queryList(page, param);
		PageInfo<ArchivesDoc> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(),
				info.getRecords());
		// List<Warehouse> collect =
		// base.stream().sorted(Comparator.comparing(Warehouse::getSort))
		// .collect(Collectors.toList());

		// 扩展列明
		QueryWrapper<ArchivesDocExt> queryWrapperDossierExt = new QueryWrapper<>();
		queryWrapperDossierExt.eq("extType", extType);
		queryWrapperDossierExt.eq("fondsNum", fondsNum);
		queryWrapperDossierExt.eq("fileType", "dossier");
		List<ArchivesDocExt> colExtList = archivesDocExtMapper.selectList(queryWrapperDossierExt);

		List<Long> ids = new ArrayList<Long>();
		List<ArchivesDoc> tempList = data.getList();
		if (tempList.size() > 0 && colExtList.size() > 0) {
			for (int i = 0; i < data.getList().size(); i++) {
				ids.add(tempList.get(i).getId());
			}
			QueryWrapper<ArchivesDocValue> queryWrapperValue = new QueryWrapper<>();
			queryWrapperValue.in("docId", ids);
			List<ArchivesDocValue> valueList = archivesDocValueMapper.selectList(queryWrapperValue);
			if (valueList.size() > 0) {
				for (int i = 0; i < tempList.size(); i++) {
					ArchivesDoc archivesDossier = tempList.get(i);
					List<ArchivesDocValue> tempCollect = valueList.stream()
							.filter(s -> s.getDocId().equals(archivesDossier.getId())).collect(Collectors.toList());
					if (tempCollect.size() > 0) {
						for (int j = 0; j < tempCollect.size(); j++) {
							ArchivesDocValue archivesDocValue = tempCollect.get(j);
							Map<String, Object> map = new HashMap<>();
							map.put("columnId", archivesDocValue.getColumnId());
							map.put("columnValue", archivesDocValue.getColumnValue());
							map.put("docId", archivesDocValue.getDocId());
							map.put("id", archivesDocValue.getId());
							map.put(archivesDocValue.getColumnId(), archivesDocValue.getColumnValue());
							Map<String, Object> ext = archivesDossier.getExt();
							ext.put(archivesDocValue.getColumnId(), archivesDocValue.getColumnValue());
							archivesDossier.setExt(ext);
							tempList.set(i, archivesDossier);
						}
					}
				}
				data.setList(tempList);
			}
		}
		ArchivesList list = new ArchivesList();
		// list.setBaseCol(collect);
		list.setListData(data);
		list.setExtCol(colExtList);
		list.setExtData(null);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", list);
	}

	@Override
	public Result<ArchivesDetails> details(ArchivesDoc archivesDossier) {
		ArchivesDetails archivesDetails = new ArchivesDetails();
		QueryWrapper<ArchivesType> queryWrapperType = new QueryWrapper<ArchivesType>();
		queryWrapperType.eq("fondsNum", archivesDossier.getFondsNum());
		queryWrapperType.eq("typeNum", archivesDossier.getTypeNum());
		List<ArchivesType> list = archivesTypeMapper.selectList(queryWrapperType);
		if (list != null && list.size() > 0) {
			QueryWrapper<ArchivesTypeDoc> col = new QueryWrapper<>();
			col.eq("extType", "dossier");
			col.eq("isQuery", "1");
			col.eq("typeId", list.get(0).getId());
			List<ArchivesTypeDoc> baseCols = archivesTypeDocMapper.selectList(col);
			
			QueryWrapper<ArchivesTypeDoc> col1 = new QueryWrapper<>();
			col1.eq("extType", "dossier");
			col1.eq("isList", "1");
			col1.eq("typeId", list.get(0).getId());
			List<ArchivesTypeDoc> baseCols1 = archivesTypeDocMapper.selectList(col);
			
			archivesDetails.setBaseCol(baseCols1);
			List<String> query = new ArrayList<>();
			for (int i = 0; i < baseCols.size(); i++) {
				query.add(baseCols.get(i).getExtColumn());
			}
			QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<ArchivesDoc>();
			for (String queryCol : query) {
				queryWrapperDoc.select(queryCol);
			}
			queryWrapperDoc.eq("id", archivesDossier.getId());
			List<ArchivesDoc> selectList = archivesDocMapper.selectList(queryWrapperDoc);
			if (selectList != null && selectList.size() > 0) {
				ArchivesDoc archivesDoc2 = selectList.get(0);
				archivesDetails.setData(archivesDoc2);
			} else {

			}
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", archivesDetails);
	}

	@Override
	public Result<String> dossierEdit(ArchivesDoc archivesDossier) {
		try {

			Map<String, List<ArchivesTypeDoc>> mapkey = new HashMap<>();
			Map<String, List<ArchivesTypeDoc>> map = new HashMap<>();
			List<ArchivesTypeDoc> typeDocs = archivesTypeDocMapper.selectList(null);
			QueryWrapper<ArchivesType> queryType = new QueryWrapper<ArchivesType>();
			queryType.eq("fondsNum", archivesDossier.getFondsNum());
			queryType.eq("typeNum", archivesDossier.getTypeNum());
			List<ArchivesType> types = archivesTypeMapper.selectList(queryType);
			for (ArchivesType archivesType : types) {
				mapkey.put(archivesType.getFondsNum() + ":" + archivesType.getId(), null);
			}
			for (String key : mapkey.keySet()) {
				List<ArchivesTypeDoc> tempList = new ArrayList<ArchivesTypeDoc>();
				// String fileType="";
				for (ArchivesTypeDoc archivesTypeDoc : typeDocs) {
					String typeId = archivesTypeDoc.getTypeId().toString();
					if (key.split(":")[1].equals(typeId)) {
						tempList.add(archivesTypeDoc);

					}
				}
				map.put(key.split(":")[0], tempList);
			}

			int updateById = archivesDocMapper.updateById(archivesDossier);
			if(updateById>0) {
				QueryWrapper<ArchivesDoc> queryWrapperDocList=new QueryWrapper<ArchivesDoc>();
				queryWrapperDocList.eq("dossierId", archivesDossier.getId());
				List<ArchivesDoc> selectList = archivesDocMapper.selectList(queryWrapperDocList);
				if(selectList!=null&&selectList.size()>0) {
					List<Long> docIds=new ArrayList<Long>();
					for (ArchivesDoc archivesDoc : selectList) {
						docIds.add(archivesDoc.getId());
					}
					QueryWrapper<ArchivesDoc> updateWrapper=new QueryWrapper<ArchivesDoc>();
					updateWrapper.in("id", docIds);
					ArchivesDoc updateEntity=new ArchivesDoc();
					updateEntity.setArchivalNum(archivesDossier.getArchivalNum());
					updateEntity.setFondsNum(archivesDossier.getFondsNum());
					updateEntity.setTypeNum(archivesDossier.getTypeNum());
					updateEntity.setClassNum(archivesDossier.getClassNum());
					updateEntity.setClassName(archivesDossier.getClassName());
					updateEntity.setArchivalYear(archivesDossier.getArchivalYear());
					updateEntity.setCategoryNum(archivesDossier.getCategoryNum());
					updateEntity.setDeptId(archivesDossier.getDeptId());
					updateEntity.setDeptName(archivesDossier.getDeptName());
					updateEntity.setDossierNum(archivesDossier.getDossierNum());
					updateEntity.setStoragePeriod(archivesDossier.getStoragePeriod());
					archivesDocMapper.update(updateEntity, updateWrapper);
				}
				
			}
			/*
			 * if (rows > 0) { QueryWrapper<ArchivesDocValue> wrapperDel = new
			 * QueryWrapper<>(); wrapperDel.eq("docId", archivesDossier.getId());
			 * archivesDocValueMapper.delete(wrapperDel); Map<String, Object> ext =
			 * archivesDossier.getExt(); for (String key : ext.keySet()) {
			 * QueryWrapper<ArchivesDocExt> queryWrapper = new QueryWrapper<>();
			 * queryWrapper.eq("extType", archivesDossier.getTypeNum());
			 * queryWrapper.eq("fondsNum", archivesDossier.getfondsNum());
			 * queryWrapper.eq("id", key); List<ArchivesDocExt> tempList =
			 * archivesDocExtMapper.selectList(queryWrapper); if (tempList != null &&
			 * tempList.size() > 0) { ArchivesDocExt archivesDocExt = tempList.get(0);
			 * ArchivesDocValue value = new ArchivesDocValue();
			 * value.setColumnId(archivesDocExt.getId());
			 * value.setColumnValue(ext.get(key).toString());
			 * value.setDocId(archivesDossier.getId());
			 * archivesDocValueMapper.insert(value); } } } else { return
			 * ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作失败！！！", ""); }
			 */
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", "");
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
	}

	@Override
	public List<Map<String, Object>> printGetDossierInfo(List<String> ids, String typeNum, String fondsNum) {
		QueryWrapper<ArchivesBase> queryBaseCol = new QueryWrapper<ArchivesBase>();
		queryBaseCol.eq("extType", "dossier");
		List<ArchivesBase> baseCol = archivesBaseMapper.selectList(queryBaseCol);
		QueryWrapper<ArchivesDocExt> queryExtCol = new QueryWrapper<>();
		queryExtCol.eq("extType", typeNum);
		queryExtCol.eq("fondsNum", fondsNum);
		queryExtCol.eq("fileType", "dossier");
		List<ArchivesDocExt> extCol = archivesDocExtMapper.selectList(queryExtCol);
		List<String> colList = new ArrayList<String>();
		for (ArchivesBase archivesBase : baseCol) {
			colList.add(archivesBase.getExtColumn());
		}
		for (ArchivesDocExt archivesDossierExt : extCol) {
			colList.add(archivesDossierExt.getExtColumn());
		}
		QueryWrapper<ArchivesDoc> queryWrapperDoc = new QueryWrapper<>();
		queryWrapperDoc.select(colList.toArray(new String[0]));
		queryWrapperDoc.in("id", ids);
		List<ArchivesDoc> baseDoc = archivesDocMapper.selectList(queryWrapperDoc);
		List<ArchivesDocValue> dossierValueList = new ArrayList<ArchivesDocValue>();
		if (ids != null && ids.size() > 0) {
			QueryWrapper<ArchivesDocValue> queryExtValue = new QueryWrapper<>();
			queryExtValue.in("docId", ids);
			dossierValueList = archivesDocValueMapper.selectList(queryExtValue);
		}
		List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
		for (ArchivesDoc archivesDossier : baseDoc) {
			Map<String, Object> parseObject = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(archivesDossier),
					Map.class);
			for (ArchivesDocValue archivesDossierValue : dossierValueList) {
				if (archivesDossierValue.getDocId().equals(archivesDossier.getId().toString())) {
					ArchivesDocExt selectById = archivesDocExtMapper.selectById(archivesDossierValue.getColumnId());
					if (selectById != null)
						parseObject.put(archivesDossierValue.getColumnValue(), archivesDossierValue.getColumnValue());
				}
			}
			map.add(parseObject);
		}

		return map;
	}

}
